import json
from random import choice
from sys import flags


class Admin: #管理员类
    def __init__(self, username, password):
        self.username = username
        self.password = password

    def admin_login_xzx(self, username, password):    #管理员登录
        if self.username == username and self.password == password:
            print("登录成功！")
            return True
        else:
            print("用户名或密码错误！")
            return False

class ProductType:
    def __init__(self, type_name):
        self.type_name = type_name

class TypeManage:   #商品分类管理类
    def __init__(self,filename):
        self.filename = filename
        self.types = self.load_types_xzx()

    def save_types_xzx(self):
        with open(self.filename, 'w',encoding='utf-8') as file:
            json.dump(list(self.types.keys()), file, indent=4) #json.dump()以字典形式写入json文件，list()转换成了队列的形式

    def load_types_xzx(self):
        with open(self.filename, 'r',encoding='utf-8') as file:
            return {k: ProductType(k) for k in json.load(file)}  #json.load()把json里的内容转换成字典的形式，{k:v for v in 。。。}这个是字典推导式  key value

    def add_type_xzx(self, type):
        if type.type_name in self.types:
            raise ValueError("类别 已存在")
        self.types[type.type_name] = type
        self.save_types_xzx()

    def change_tyge_xzx(self, old_type_name, new_type_name):
        if old_type_name not in self.types:
            raise ValueError("类别 不存在")
        self.types[new_type_name] = self.types.pop(old_type_name)
        self.save_types_xzx()

    def delete_type_xzx(self, type_name):
        if type_name in self.types:
            del  self.types[type_name]
            self.save_types_xzx()
        else:
            raise ValueError("类别 不存在")




class Product:  #商品类
    def __init__(self, barcode, name , type, description, price, quantity, status):  #商品元素属性
        self.barcode = barcode
        self.name = name
        self.type = type
        self.description = description
        self.price = price
        self.quantity = quantity
        self.status = status

    def save_dict_xzx(self):
        return {
            'barcode': self.barcode,
            'name': self.name,
            'type': self.type,
            'description': self.description,
            'price': self.price,
            'quantity': self.quantity,
            'status': self.status
        }

    @staticmethod
    def load_dict_xzx(data):
        return Product(data['barcode'], data['name'], data['type'], data['description'], data['price'],
                       data['quantity'], data['status'])

class ProductManager:     #商品管理类
    def __init__(self,filename):
        self.filename = filename
        self.products = self.load_products_xzx()


    def save_products_xzx(self):
        with open(self.filename, 'w',encoding='utf-8') as file:
            json.dump({k: v.save_dict_xzx() for k, v in self.products.items()}, file, indent=4)  #save_dict_xzx()创建一个字典成为总字典的键值 {k:v for v in 。。。}这个是字典推导式，这里的意思是遍历整个json文件

    def load_products_xzx(self):
        with open(self.filename, 'r',encoding='utf-8') as file:
            return {str(k): Product.load_dict_xzx(v) for k, v in json.load(file).items()}   #这里的字典推导式是把json里的数据转换成字典形式输出， 其中load_dict_xzx(v)是把每个键值的字典按函数编写的顺序输出

    def add_product_xzx(self, product):
        if product.barcode in self.products:
            raise ValueError("产品已存在")
        self.products[product.barcode] = product
        self.save_products_xzx()

    def change_product_xzx(self, barcode, **kwargs):   #**kwargs这是魔法变量，可以输入多个表达式
        if barcode not in self.products:
            raise ValueError("产品不存在")
        product = self.products[barcode]
        for key, value in kwargs.items():
            setattr(product, key, value)
        self.save_products_xzx()

    def delete_product_xzx(self, barcode):
        if barcode in self.products:
            del self.products[barcode]
            self.save_products_xzx()
        else:
            raise ValueError("产品不存在")

    def query_product_xzx(self, barcode):
        if barcode in self.products:
            with open(self.filename, 'r', encoding='utf-8') as file:
                load_dict=json.load(file)
            return load_dict.get(barcode)  #用get方法获取该条形编码的数据
        else:
            raise ValueError("产品不存在")

def change_product_info_xzx(product_manager):
    barcode = input("请输入要修改的商品条形码：")
    if barcode not in product_manager.products:
        print("商品不存在！")
        return
    new_name = input("请输入新的商品名称：")
    new_type = input("请输入新的商品分类：")
    new_description = input("请输入新的商品描述：")
    new_price = float(input("请输入新的价格："))
    new_quantity = int(input("请输入新的数量："))
    new_status = input("请输入新的状态（上架或下架）：")
    new_product_info = {
        'name': new_name,
        'type': new_type,
        'description': new_description,
        'price': new_price,
        'quantity': new_quantity,
        'status': new_status
    }
    product_manager.change_product_xzx(barcode, **new_product_info)
    print("商品信息修改成功！")

class User:
    def __init__(self, username, password, nickname=None, role='user', status='online', email=None, phone=None):
        self.username = username
        self.password = password
        self.nickname = nickname
        self.role = role
        self.status = status
        self.email = email
        self.phone = phone
    def save_dict_xzx(self):
        return {
            'username': self.username,
            'password': self.password,
            'nickname': self.nickname,
            'role': self.role,
            'status': self.status,
            'email': self.email,
            'phone': self.phone
        }

    @staticmethod   #静态方法
    def lord_dict_xzx(data):
        return User(data['username'], data['password'], data['nickname'], data['role'], data['status'], data['email'],
                    data['phone'])


class UserManager:
    def __init__(self, filename):
        self.filename = filename
        self.users = self.load_users_xzx()

    def load_users_xzx(self):
        with open(self.filename, 'r',encoding='utf-8') as file:
            return {k: User.lord_dict_xzx(v) for k, v in json.load(file).items()}


    def save_users_xzx(self):
        with open(self.filename, 'w',encoding='utf-8') as file:
            json.dump({k: v.save_dict_xzx() for k, v in self.users.items()}, file, indent=4)

    def register_user_xzx(self, user):
        if user.username in self.users:
            raise ValueError("用户已存在")
        self.users[user.username] = user
        self.save_users_xzx()

    def user_login_xzx(self, username, password):
        if username in self.users and self.users[username].password == password:
            return True
        else:
            return False

    def add_user_xzx(self, user):
        if user.username in self.users:
            raise ValueError("用户已存在")
        self.users[user.username] = user
        self.save_users_xzx()

    def change_user_xzx(self, username, **kwargs):
        if username not in self.users:
            raise ValueError("用户未存在")
        user = self.users[username]
        for key, value in kwargs.items():
            setattr(user, key, value)
        self.save_users_xzx()

    def delete_user_xzx(self, username):
        if username in self.users:
            del self.users[username]
            self.save_users_xzx()
        else:
            raise ValueError("用户未存在")

    def query_user_xzx(self, username):
        if username in self.users:
            with open(self.filename, 'r', encoding='utf-8') as file:
                load_dict=json.load(file)
            return load_dict.get(username)
        else:
            raise ValueError("用户不存在")


def change_user_info_xzx(user_manager):
    username = input("请输入要修改的用户名：")
    if username not in user_manager.users:
        print("用户不存在！")
        return
    new_password = input("请输入新的密码：")
    new_nickname = input("请输入新的昵称(选填)：")
    new_role = input("请输入新的权限(用户或管理员)：")
    new_status = input("请输入新的状态(正常或封号)：")
    new_email = input("请输入新的邮箱 (选填)：")
    new_phone = input("请输入新的手机号 (选填)：")
    new_user_info = {
        'password': new_password,
        'nickname': new_nickname,
        'role': new_role,
        'status': new_status,
        'email': new_email,
        'phone': new_phone
    }
    user_manager.change_user_xzx(username, **new_user_info)
    print("用户信息修改成功！")

def register_user_xzx(user_manager):
    username = input("请输入用户名: ")
    password = input("请输入密码: ")
    nickname = input("请输入昵称(选填): ")
    role = input("请输入权限(用户或管理员): ")
    status = str(input("请输入状态(正常或封号): "))
    email = input("请输入邮箱 (选填): ")
    phone = input("请输入手机号 (选填): ")

    user = User(username, password, nickname, role, status, email, phone)
    try:
        user_manager.register_user_xzx(user)
        print(f"用户 {username} 注册成功.")
    except ValueError as e:
        print(e)

def user_login_xzx(user_manager):
    username = input("请输入用户名: ")
    password = input("请输入密码: ")
    if user_manager.user_login_xzx(username, password):
        print("登录成功")
        return True
    else:
        print("用户名或密码无效.")
        return False


def main():
    # 创建商品管理实例
    product_manager = ProductManager('products.json')
    # 创建商品分类管理实例
    type_manager=TypeManage('types.json')
    # 创建用户管理实例
    user_manager = UserManager('users.json')

    # 创建管理员实例
    admin = Admin('admin', 'password123')
    admin_flag=False
    user_flag=False
    choice=-1
    while choice not in [1, 2, 3]:
        print("功能选择：1.登录功能 2.分类管理 3.商品管理 ")
        # 判断是不是是数字
        choice = input()
        if not choice.isdigit():
            print("输入错误,请再输入一次")
            continue
        elif int(choice)==1:
            while choice not in [1, 2, 3]:
                print("登录功能：1.管理员界面  2.用户界面  3.返回 ")
                choice = input()
                if not choice.isdigit():
                    print("输入错误,请再输入一次")
                    continue
                elif int(choice)==1:
                    while choice not in [1, 2, 3]:
                        print("管理员界面：1.登录  2.用户管理  3.返回 ")
                        choice = input()
                        if not choice.isdigit():
                            print("输入错误,请再输入一次")
                            continue
                        elif int(choice)==1:
                            print("管理员正在登录...")
                            if admin.admin_login_xzx(input("请输入账号：\n"), input("请输入密码：\n")):
                                print("管理员已成功登录。")
                                admin_flag = True
                            else:
                                print("管理员登录失败。")
                                continue
                        elif int(choice) == 2:
                            while choice not in [1, 2, 3,4]:
                                print("用户管理：1.增加新用户  2.修改用户  3.删除用户  4.查看用户信息  5.返回 ")
                                choice = input()
                                if not choice.isdigit():
                                    print("输入错误,请再输入一次")
                                    continue
                                elif int(choice)==1:
                                    if not admin_flag:
                                        print("用户未登录或没有权限")
                                        break
                                    print("\n增加新用户..")
                                    register_user_xzx(user_manager)
                                elif int(choice)==2:
                                    if not admin_flag:
                                        print("用户未登录或没有权限")
                                        break
                                    print("\n修改用户..")
                                    change_user_info_xzx(user_manager)
                                elif int(choice) == 3:
                                    if not admin_flag:
                                        print("用户未登录或没有权限")
                                        break
                                    user_manager.delete_user_xzx(input("输入要删除的用户名："))
                                elif int(choice) == 4:
                                    if not admin_flag:
                                        print("用户未登录或没有权限")
                                        break
                                    print(user_manager.query_user_xzx(username=input("请输入用户名：")))

                                else:
                                    break
                        else:
                            break
                elif int(choice)==2:
                    while choice not in [1, 2, 3]:
                        print("用户界面：1.登录  2.注册  3.返回 ")
                        choice = input()
                        if not choice.isdigit():
                            print("输入错误,请再输入一次")
                            continue
                        elif int(choice)==1:
                            print("\n用户登录...")
                            if user_login_xzx(user_manager):
                                user_flag=True
                        elif int(choice)==2:
                            print("\n注册用户...")
                            register_user_xzx(user_manager)
                        else:
                            break
                else:
                    break
        elif int(choice)==2:
            while choice not in [1, 2,3,4]:
                print("分类管理：1.增加商品类型 2.修改商品类型  3.删除商品类型 4.返回 ")
                choice = input()
                if not choice.isdigit():
                    print("输入错误,请再输入一次")
                    continue
                elif int(choice) == 1:
                    if not admin_flag:
                        print("用户未登录或没有权限")
                        break
                    print("\n添加商品类型...")
                    type_manager.add_type_xzx(ProductType(str(input("请输入商品类别："))))
                elif int(choice) == 2:
                    if not admin_flag:
                        print("用户未登录或没有权限")
                        break
                    print("\n修改商品类型")
                    type_manager.change_tyge_xzx(input("输入旧商品分类:"),input("\n输入新商品分类:"))
                elif int(choice) == 3:
                    if not admin_flag:
                        print("用户未登录或没有权限")
                        break
                    print("\n删除商品类型...")
                    type_manager.delete_type_xzx(input("输入要删除的商品类别："))
                else:
                    break
        else:
            while choice not in [1, 2,3,4,5]:
                print("商品管理：1.增加商品 2.修改商品 3.删除商品 4.查询商品 5.返回 ")
                choice = input()
                if not choice.isdigit():
                    print("输入错误,请再输入一次")
                    continue
                elif int(choice) == 1:
                    if not admin_flag:
                        print("用户未登录或没有权限")
                        break
                    print("\n添加商品...")
                    product_manager.add_product_xzx(Product(input("\n请输入商品条码:"), input("\n请输入商品名称:"), input("\n请输入商品分类:"), input("\n请输入商品简介:"), input("\n请输入价格:"), input("\n请输入数量:"), input("\n请输入状态:")))
                elif int(choice) == 2:
                    if not admin_flag:
                        print("用户未登录或没有权限")
                        break
                    print("\n修改商品")
                    change_product_info_xzx(product_manager)
                elif int(choice) == 3:
                    if not admin_flag:
                        print("用户未登录或没有权限")
                        break
                    print("\n删除商品...")
                    product_manager.delete_product_xzx(input("\n请输入要删除商品的商品条码："))
                elif int(choice) == 4 :
                    if not user_flag and not admin_flag:
                        print("用户未登录或没有权限")
                        break
                    print(product_manager.query_product_xzx(barcode=input("请输入商品条码：")))
                else:
                    break



if __name__ == "__main__":
    main()

























